/**
 * Created with JetBrains PhpStorm.
 * User: jiangshuguang
 * Date: 14-10-19
 * Time: 下午4:31
 * To change this template use File | Settings | File Templates.
 */

exports.Dialog = P.createUi({
    _data:{
        title:'提示',
        content:'',
        onClose:function(){},
        onShow:function(){},
        autoClose:false, //是否点击空白区域关闭
        model:'dialog',//[tip[dialog]]
        buttons:[
            {
                text:'知道了',
                class:'',
                events:[
                    {
                        type:'touchstart',
                        event:function(callback){
                            callback();
                        }
                    }
                ]
            }
        ]
    },
    _create:function(){
        var me = this,
            buttons = this.data('buttons'),
            $root = $('' +
            '<div class="zrb-ui-dialog">' +
                '<div class="dialog-container">' +
                    '<div class="dialog-header">' +
                        '<span>'+this.data('title')+'</span>' +
                        '<a class="btn-close"></a>' +
                    '</div>' +
                    '<div class="dialog-content">'+ this.data('content')+'</div>' +
                    '<div class="dialog-footer"></div>'+
                '</div>' +
            '</div>' +
            '').appendTo('body');

        if(this.data('model') == 'dialog'){
            $.each(this.data('buttons'),function(k,v){
                var $btn = $('<a class="btn btn-large">'+ v.text+'</a>').appendTo($root.find('.dialog-footer'));
                !!v.class && $btn.addClass(v.class);
                if(v.events){
                    $.each(v.events,function(k1,v1){
                        $btn.on(v1.type,function(){
                            v1.event(function(){
                                me.hide();
                            });
                        });
                    });
                }
            });
        }

        this.data({
            '$root':$root,
            '$container':$root.find('.dialog-container'),
            '$header':$root.find('.dialog-header'),
            '$content':$root.find('.dialog-content'),
            '$footer':$root.find('dialog-footer')
        });
    },

    _init:function(){
        var me = this;
        this.data('$header').find('.btn-close').on('touchstart',function(){
            me.hide();
        });

        this.data('$root').on('touchstart',function(){
            if(me.data('autoClase')){
                me.hide();
            }
        });
    },

    show:function(content){
        this.trigger('show');
        content && this.data('$content').html(content);
        this.data('$root').show();
        var height = this.data('$container').height();
        this.data('$container').css('margin-top','-'+(height/2)+'px');
    },

    hide:function(){
       this.trigger('close');
       this.data('$root').hide();
    }
});
